﻿using jvm.classfile.attributeinfo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*
field_info {
    u2             access_flags;
    u2             name_index;
    u2             descriptor_index;
    u2             attributes_count;
    attribute_info attributes[attributes_count];
}
method_info {
    u2             access_flags;
    u2             name_index;
    u2             descriptor_index;
    u2             attributes_count;
    attribute_info attributes[attributes_count];
}
*/
namespace jvm.classfile
{
    class JMemberInfo
    {
        public ushort access_flags;
        public ushort name_index;
        public ushort descriptor_index;
        public AttributeInfo[] attributeInfos;

        public ConstantPool pool; // 缓存

        public void Read(ClassReader reader)
        {
            access_flags = reader.ReadUshort();
            name_index = reader.ReadUshort();
            descriptor_index = reader.ReadUshort();
            ushort attributes_count = reader.ReadUshort();
            attributeInfos = new AttributeInfo[attributes_count];
            for (int i = 0; i < attributes_count; i++)
            {
                attributeInfos[i] = AttrFactory.Create(reader, pool);
                attributeInfos[i].Read(reader);
            }
        }

        public string Name()  {
            return pool.GetUtf8(name_index);
        }

        public string Descriptor()
        {
            return pool.GetUtf8(descriptor_index);
        }

        public CodeAttribute CodeAttribute()
        {
            foreach (AttributeInfo attrInfo in attributeInfos)
            {
                if (attrInfo.GetType() == typeof(CodeAttribute))
                {
                    return (CodeAttribute)attrInfo;
                }
            }
            return null;
        }

        public ConstantValueAttribute ConstantValueAttribute()
        {
            foreach (AttributeInfo attrInfo in attributeInfos)
            {
                if (attrInfo.GetType() == typeof(ConstantValueAttribute))
                {
                    return (ConstantValueAttribute)attrInfo;
                }
            }
            return null;
        }
    }
}
